package com.kingyea.mobilepolice.systemsync;

import com.kingyea.mobilepolice.redis.service.RedisService;
import com.kingyea.mobilepolice.redis.service.RedisSyncService;
import com.kingyea.mobilepolice.systemsync.bean.InvokedMethod;
import com.kingyea.mobilepolice.util.GlobalVar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * @author cxc
 * @version v1.0.0
 * @description bean加载到spring容器后执行同步数据线程
 * @date Created in 2018.04.19 11:54
 */

@Component
public class SyncThread implements InitializingBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(SyncThread.class);

    // 待执行队列
    public static LinkedBlockingQueue<InvokedMethod> toBeInvokSyncQueue = new LinkedBlockingQueue();

    @Autowired
    private RedisSyncService redisSyncService;

    @Autowired
    private SystemSyncService systemSyncService;

    @Value("${kingyea.mobilepolice.inside}")
    private Integer inside;

    @Override
    public void afterPropertiesSet() {

        new Thread(() -> {
            SyncInvokMethodProxy sync = new SyncInvokMethodProxy(redisSyncService, RedisService.class);
            while (true) {
                InvokedMethod bean = null;
                try {
                    bean = toBeInvokSyncQueue.take();//消费队列，无元素阻塞
                    if (bean == null) continue;
                    // 同步操作
                    sync.invokService(bean);
                    LOGGER.info("【同步操作成功 +1】", bean);
                } catch (Exception e) {
                    LOGGER.error("【同步操作失败 +1】", bean);
                    LOGGER.error("【同步数据线程异常】", e);
                }
            }
        }).start();

        // 外网的token同步定时任务，主要是把内网的token信息同步出来
        if (inside.intValue() == GlobalVar.insideWai) {
            ScheduledExecutorService syncToeknServer4wai = Executors.newSingleThreadScheduledExecutor();// 服务关闭时，该任务线程是否结束？
            ScheduledFuture<?> scheduledFuture = syncToeknServer4wai.scheduleWithFixedDelay(() -> {
                try {
                    systemSyncService.syncJob();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }, 13, 5, TimeUnit.SECONDS);
        }

    }


}
